<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.name" placeholder="请输入查询的关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
    <el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="120" >
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="100" >
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" :formatter="formatSex" sortable>
        <template scope="scope">
          <span v-if="scope.row.state == 1" style="color: green">启用</span>
          <span v-else-if="scope.row.state == 0" style="color: red">禁用</span>
          <span v-else>未知</span>
        </template>

      </el-table-column>
      <el-table-column prop="manager.username" label="负责人" width="120" >
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" min-width="180" >
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" v-perm="'department:deleteById'" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :current-page="currentPage" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="部门名称" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>

        <el-form-item label="部门经理" >
<!--          <el-input v-model="editForm.manager" auto-complete="off"></el-input>-->
          <!-- 需要作下拉选择 在elmentUI去找
                el-select : 下拉选择
                el-option : 每行显示的内容
                v-for : 循环employees
                :key ：元素的唯一标识
                :label :确认选择完成后选择框里展示的内容
                :value ：要提交到后台的值
          -->
          <el-select v-model="editForm.manager" value-key="id" placeholder="请选择">
            <el-option
                v-for="employee in employees"
                :key="employee.id"
                :label="employee.username"
                :value="employee">
              <span style="float: left">{{ employee.username }}</span> <!--下拉后选择框里面显示的值-->
              <span style="float: right; color: #8492a6; font-size: 13px">{{ employee.phone }}</span> <!--下拉后选择框里面显示的值-->
            </el-option>
          </el-select>


        </el-form-item>

        <el-form-item label="上级部门" >
<!--          <el-input v-model="editForm.parent" auto-complete="off"></el-input>-->
          <el-cascader v-model="editForm.parent"
                       :options="tree"
                       :props="{ checkStrictly: true,value:'id',label:'name'}"
                       clearable></el-cascader>
        </el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>


	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';

	export default {
		data() {
			return {
			  title:'',
				filters: {
					name: ''
				},
        keyWord:'',
				departments: [],
        employees: [],
        tree: [],
				total: 0,
				pageSize: 5,
        currentPage: 1,
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					name: [
						{ required: true, message: '请输入部门名称', trigger: 'blur' }
					],
          sn: [
            { required: true, message: '请输入部门编号', trigger: 'blur' }
          ]
				},
				//编辑或新增界面数据
				editForm: {
					id: null,
					name: '',
          sn: '',
					state: 1,
					age: 0,
          manager: null,
          parent: null
				}
			}
		},
		methods: {
		  search(){
		    this.currentPage = 1;
		    this.getDepartments();
      },
			//性别显示转换
			formatSex: function (row, column) {
				return row.state == 1 ? '启用' : row.state == 0 ? '禁用' : '未知';
			},
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getDepartments();
			},
			//获取部门列表
			getDepartments() {
				let para = {
					pageSize: this.pageSize,
          currentPage: this.currentPage,
					keyWord: this.filters.name
				};
				this.listLoading = true;/* 开启数据加载盲等 */

				/* 开始向后端发送请求  需要main里面配置axios */
        this.$http.post("/dept",para).
        then(res=>{
          this.listLoading = false;/* 关闭数据加载盲等 */
          console.log(res)
          this.departments = res.data.data/* 把当前页的数据给模型层 */
          this.total = res.data.totals
        }).catch(res=>{
        })
			},
			//删除
			handleDel: function (index,row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
				  /* 点击确认就执行then里面的函数 */
					this.listLoading = true;  /* 盲等 */
					//NProgress.start();
					let para = { id: row.id };  /*  获取id*/

          /* 发送删除请求 */
          this.$http.delete("/dept/"+row.id)
              .then(res=>{
                this.listLoading = false;/* 关闭盲等 */
                if(res.data.success){
                  this.$message({
                    showClose: true,
                    message: '删除成功',
                    type: 'success'
                  });
                  this.currentPage = 1;/* 删除后回到首页 这个根据公司的实际需求来定 */
                  this.getDepartments(); /* 刷新页面 */
                }else{
                  this.$message({
                    message: '删除失败',
                    type: 'error'
                  });
                }
              })/* 请求发送成功 */
              .catch(res=>{
                this.$message({
                  message: '请求发送失败',
                  type: 'error'
                });
              })/* 请求发送失败 */


				}).catch(() => {/* 点击取消就执行catch里面的函数 (什么都不执行) */

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
        this.getTree();
		    this.title = "编辑";
				this.editFormVisible = true;
				this.editForm = Object.assign({}, row);

				let dirPath = this.editForm.dirPath;
        let dirPath1 = dirPath.split("/")

        let dirPathPara = [];
        for (let i= 1;i<dirPath1.length-1;i++) {
          dirPathPara.push(parseInt(dirPath1[i]))/*parseInt():将字符串转为数组  */
        }
				/* 回显dir_path */
				this.editForm.parent = dirPathPara;


			},

			//显示新增界面
			handleAdd: function () {
		    this.getTree();
		    this.title = "新增";
				this.editFormVisible = true;//开启对话框
				this.editForm = { //清空表单
          id: null,
          name: '',
          sn: '',
          state: 1,
          age: 0,
          manager: null,
          parent: null
				};
			},
			//编辑
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {//$refs.editForm :主动校验规则
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;//开启盲等
							//NProgress.start();
							let para = Object.assign({}, this.editForm); //表单拷贝  然后在这个拷贝下来的表单里面做操作
              let arr = para.parent;
              if (arr){
                let parmParentObj = {id: arr[arr.length-1]};
                para.parent = parmParentObj;
              }





							//发起提交表单请求
              this.$http.put("/dept",para)
                  .then(res=>{
                    this.editLoading = false;//关闭盲等
                    if (res.data.success){
                      this.editFormVisible = false;//关闭对话框
                      this.$message({
                        showClose: true,
                        message: '操作成功',
                        type: 'success'
                      });
                      this.getDepartments();//刷新列表
                    }else{
                      this.$message.error(res.data.message)
                    }

                  })
                  .catch(res=>{
                    this.$message.error("请求发送失败")
                  })

						});
					}
				});
			},

			selsChange: function (sels) {
				this.sels = sels;
			},

			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);/* 把行数组转为id数组 */
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();


					//发送批量删除请求
          this.$http.patch("/dept",ids)
              .then(res=>{
                this.listLoading = false;/* 关闭盲等 */
                if(res.data.success){
                  this.$message({
                    showClose: true,
                    message: '删除成功',
                    type: 'success'
                  });
                  this.currentPage = 1;/* 删除后回到首页 这个根据公司的实际需求来定 */
                  this.getDepartments(); /* 刷新页面 */
                }else{
                  this.$message({
                    message: '删除失败',
                    type: 'error'
                  });
                }
              })/* 请求发送成功 */
              .catch(res=>{
                this.$message({
                  message: '请求发送失败',
                  type: 'error'
                });
              })/* 请求发送失败 */

				}).catch(() => {

				});
			},

      //查询所有员工 发送请求
      getEmployees: function () {
		    this.$http.get("employee",)
            .then(res=>{
              this.employees = res.data;
              console.log(res);
            })
            .catch(res=>{
              this.$message.error("获取员工请求发送失败")
            })
      },

      //查询部门树状结构
      getTree: function (){
		    this.$http.get("/dept/getTree")
            .then(res=>{
              this.tree = res.data;
              console.log(res);
            })
            .catch(res=>{
              this.$message.error("获取树状部门请求发送失败")
            })
      }
		},
		mounted() {/* （钩子函数）页面加载完成后就执行 */
			this.getDepartments();/* 调用获取数据的方法 */
      this.getEmployees(); //调用获取所有员工的方法
		}
	}

</script>

<style scoped>

</style>